import { mapGetters } from 'vuex';
export default {
	data() {
		return {
			loading: false,
			queryData: { page: 1, limit: 15 },
			dataCount: 0,
			tableData: [],
			dataId: '',
			formDialog: false
		}
	},
	mounted() {
		if (!this.hasOwnProperty('activeName')) {
			this.queryTableData();
		}
	},
	methods: {
		//格式化请求参数
		async formatRequestParams() {
			if (!this.requestParams) {
				return Promise.resolve(this.queryData);
			} else {
				return Promise.resolve(this.requestParams);
			}
		},

		//获取列表数据
		async getTableData() {
			let params = await this.formatRequestParams();
			let result = await this.listFunction(params).then(res => res.data);
			if (result.code === '0') {
				this.dataCount = parseInt(result.count);
				return Promise.resolve(result.data || []);
			}
		},

		//查询列表数据
		async queryTableData() {
			this.loading = true;
			this.tableData = await this.getTableData();
			this.loading = false;
		},

		//查询数据列表
		handleQueryTableData() {
			this.queryData.page = 1;
			this.queryTableData();
		},

		handleOpenDialog(id) {
			this.dataId = !id ? '' : id;
			this.formDialog = true;
		},

		//格式化删除参数
		formatDeleteData(data) {
			let ids = Array.isArray(data) ? [] : '';
			if (Array.isArray(data)) {
				let tips = '';
				data.forEach(n => {
					ids.push(n.id);
					!!n.name && (tips += `【${n.name}】`);
				})
				return { ids, tips: !tips ? '' : `<font color="#f00">${tips}</font>` };
			} else {
				ids = data.id;
				return { ids, tips: !data.name ? '' : `<font color="#f00">【${data.name}】</font>` };
			}
		},

		handleDeleteData(data) {
			let that = this;
			let params = this.formatDeleteData(data);
			let tipString = `${!params.tips ? '该' : ''}${this.pageName}${params.tips}`;
			that.$confirm(`此操作将${this.handName || '删除'}${tipString}, 是否继续?`, `${this.handName || '删除'}提示`, {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				dangerouslyUseHTMLString: true,
				type: 'warning',
				async beforeClose(action, instance, done) {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await that.deleteDataRequest(params.ids);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		async deleteDataRequest(ids) {
			let result = await this.deleteFunction(ids).then(res => res.data);
			if (result.code === '0') {
				this.$message.success(`${this.handName || '删除'}${this.pageName}成功`);
				this.updateStoreData?.();
				this.queryTableData();
			}
		}
	}
}